package com.kjsdfgk.hjmdsf.play.mvp.ui.activity;

import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.blankj.utilcode.util.DeviceUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;

import com.jess.arms.utils.LogUtils;
import com.kjsdfgk.hjmdsf.app.entity.FavoriteItem;
import com.kjsdfgk.hjmdsf.app.entity.HistoryItem;
import com.kjsdfgk.hjmdsf.app.entity.ListBean;
import com.kjsdfgk.hjmdsf.app.entity.XJVideoJson;
import com.kjsdfgk.hjmdsf.ftvdolist.mvp.bean.XJLookResult;
import com.kjsdfgk.hjmdsf.ftvdolist.mvp.bean.XJVideo;
import com.kjsdfgk.hjmdsf.play.di.component.DaggerMyPlayVideoComponent;
import com.kjsdfgk.hjmdsf.play.mvp.contract.MyPlayVideoContract;
import com.kjsdfgk.hjmdsf.play.mvp.presenter.MyPlayVideoPresenter;
import com.lksdkjs.live.R;
import com.shuyu.gsyvideoplayer.GSYVideoManager;
import com.shuyu.gsyvideoplayer.builder.GSYVideoOptionBuilder;
import com.shuyu.gsyvideoplayer.listener.GSYSampleCallBack;
import com.shuyu.gsyvideoplayer.listener.GSYVideoProgressListener;
import com.shuyu.gsyvideoplayer.listener.LockClickListener;
import com.shuyu.gsyvideoplayer.utils.Debuger;
import com.shuyu.gsyvideoplayer.utils.OrientationUtils;
import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer;
import com.shuyu.gsyvideoplayer.video.base.GSYVideoPlayer;
import com.youth.banner.Banner;


import org.litepal.LitePal;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import cn.leancloud.AVObject;
import cn.leancloud.AVUser;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import me.jessyan.autosize.AutoSize;
import me.jessyan.autosize.internal.CancelAdapt;

import static com.jess.arms.utils.Preconditions.checkNotNull;


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 04/10/2020 12:30
 * <a href="mailto:jess.yan.effort@gmail.com">Contact me</a>
 * <a href="https://github.com/JessYanCoding">Follow me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms">Star me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms/wiki">See me</a>
 * <a href="https://github.com/JessYanCoding/MVPArmsTemplate">模版请保持更新</a>
 * ================================================
 */
public class MyPlayVideoActivity extends BaseActivity<MyPlayVideoPresenter> implements MyPlayVideoContract.View {

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerMyPlayVideoComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .view(this)
                .build()
                .inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_my_play_video; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

    @BindView(R.id.banner)
    Banner banner;
    @BindView(R.id.tv_content)
    TextView title;
    @BindView(R.id.checkbox)
    CheckBox checkBox;
    ListBean xjVideo;

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        xjVideo = (ListBean) getIntent().getSerializableExtra("bean");
        detailPlayer.getBackButton().setOnClickListener(v -> onBackPressedSupport());

        String myUrl = xjVideo.getVod_id() + "";
        String userName = SPUtils.getInstance().getString("account", "");

        if (xjVideo.getType_id() == 2100) {
            mPresenter.lookVod(xjVideo.getVod_tag());

            HistoryItem historyItem = new HistoryItem();
            historyItem.img = xjVideo.getVod_pic();
            historyItem.url = xjVideo.getVod_tag();
            historyItem.title = xjVideo.getVod_name();
            historyItem.time = TimeUtils.getNowString();
            historyItem.type = 2100;
            historyItem.userName = userName;
            List<HistoryItem> itemList = LitePal.where("url=?", historyItem.url ).find(HistoryItem.class);
            for (HistoryItem item : itemList) {
                item.delete();
            }
            myUrl=historyItem.url;
            historyItem.save();
        }else if (xjVideo.getType_id() == 2200) {
            mPresenter.lookVod(xjVideo.getVod_tag());

            HistoryItem historyItem = new HistoryItem();
            historyItem.img = xjVideo.getVod_pic();
            historyItem.url = xjVideo.getVod_tag();
            historyItem.title = xjVideo.getVod_name();
            historyItem.time = TimeUtils.getNowString();
            historyItem.type = 2200;
            historyItem.userName = userName;
            List<HistoryItem> itemList = LitePal.where("url=?", historyItem.url ).find(HistoryItem.class);
            for (HistoryItem item : itemList) {
                item.delete();
            }
            myUrl=historyItem.url;
            historyItem.save();
        } else {
            mPresenter.lookVod(xjVideo.getVod_id());

            HistoryItem historyItem = new HistoryItem();
            historyItem.img = xjVideo.getVod_pic();
            historyItem.url = xjVideo.getVod_id() + "";
            historyItem.title = xjVideo.getVod_name();
            historyItem.time = TimeUtils.getNowString();
            historyItem.type = 2000;
            historyItem.userName = userName;
            List<HistoryItem> itemList = LitePal.where("url=?", historyItem.url ).find(HistoryItem.class);
            for (HistoryItem item : itemList) {
                item.delete();
            }
            myUrl=historyItem.url;
            historyItem.save();
        }
        try {
            List<FavoriteItem> itemListxxxx = LitePal.where("url=? and userName=?",myUrl,userName).find(FavoriteItem.class);
            if (itemListxxxx.size() > 0){
                checkBox.setChecked(true);
            }else {
                checkBox.setChecked(false);
            }
        }catch (Exception e){
            AVObject avObject = new AVObject();// 新建 AVUser 对象实例
            avObject.setClassName("Log");
            String info = DeviceUtils.getManufacturer() + DeviceUtils.getModel();
            avObject.put("crash" ,"com.lksdkjs.live---->" + e.toString());//
            avObject.put("info", info);
            avObject.put("time", TimeUtils.getNowString());
            avObject.saveInBackground().subscribe(new Observer<AVObject>() {
                @Override
                public void onSubscribe(Disposable disposable) {

                }

                @Override
                public void onNext(AVObject avObject) {
                    System.out.println("saveObject field finished.");

                }

                @Override
                public void onError(Throwable throwable) {

                }

                @Override
                public void onComplete() {

                }
            });
        }


        //增加封面
        ImageView imageView = new ImageView(this);
        imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);


        //detailPlayer.setThumbImageView(imageView);

        detailPlayer.getTitleTextView().setVisibility(View.GONE);
        detailPlayer.getBackButton().setVisibility(View.VISIBLE);
        detailPlayer.getBackButton().setOnClickListener(v -> {
            onBackPressedSupport();
        });

        //外部辅助的旋转，帮助全屏
        orientationUtils = new OrientationUtils(this, detailPlayer);
        //初始化不打开外部的旋转
        orientationUtils.setEnable(false);

        /**仅仅横屏旋转，不变直*/
        //orientationUtils.setOnlyRotateLand(true);

//        Map<String, String> header = new HashMap<>();
//        header.put("ee", "33");
//        header.put("allowCrossProtocolRedirects", "true");
        GSYVideoOptionBuilder gsyVideoOption = new GSYVideoOptionBuilder();
        gsyVideoOption.setThumbImageView(imageView)
                .setIsTouchWiget(true)
                .setRotateViewAuto(false)
                //仅仅横屏旋转，不变直
                //.setOnlyRotateLand(true)
                .setLockLand(false)
                .setAutoFullWithSize(false)
                .setShowFullAnimation(false)
                .setNeedLockFull(true)
//                .setMapHeadData(header)
                .setCacheWithPlay(true)
                .setVideoAllCallBack(new GSYSampleCallBack() {
                    @Override
                    public void onPrepared(String url, Object... objects) {
                        Debuger.printfError("***** onPrepared **** " + objects[0]);
                        Debuger.printfError("***** onPrepared **** " + objects[1]);
                        super.onPrepared(url, objects);
                        //开始播放了才能旋转和全屏
                        orientationUtils.setEnable(true);
                        isPlay = true;

                        //设置 seek 的临近帧。

                    }

                    @Override
                    public void onEnterFullscreen(String url, Object... objects) {
                        super.onEnterFullscreen(url, objects);
                        Debuger.printfError("***** onEnterFullscreen **** " + objects[0]);//title
                        Debuger.printfError("***** onEnterFullscreen **** " + objects[1]);//当前全屏player
                    }

                    @Override
                    public void onAutoComplete(String url, Object... objects) {
                        super.onAutoComplete(url, objects);
                    }

                    @Override
                    public void onClickStartError(String url, Object... objects) {
                        super.onClickStartError(url, objects);
                    }

                    @Override
                    public void onQuitFullscreen(String url, Object... objects) {
                        super.onQuitFullscreen(url, objects);
                        Debuger.printfError("***** onQuitFullscreen **** " + objects[0]);//title
                        Debuger.printfError("***** onQuitFullscreen **** " + objects[1]);//当前非全屏player
                        if (orientationUtils != null) {
                            orientationUtils.backToProtVideo();
                        }
                    }
                })
                .setLockClickListener(new LockClickListener() {
                    @Override
                    public void onClick(View view, boolean lock) {
                        if (orientationUtils != null) {
                            //配合下方的onConfigurationChanged
                            orientationUtils.setEnable(!lock);
                        }
                    }
                })
                .setGSYVideoProgressListener(new GSYVideoProgressListener() {
                    @Override
                    public void onProgress(int progress, int secProgress, int currentPosition, int duration) {
                        Debuger.printfLog(" progress " + progress + " secProgress " + secProgress + " currentPosition " + currentPosition + " duration " + duration);
                    }
                })
                .build(detailPlayer);

        detailPlayer.getFullscreenButton().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //直接横屏
                orientationUtils.resolveByClick();

                //第一个true是否需要隐藏actionbar，第二个true是否需要隐藏statusbar
                detailPlayer.startWindowFullscreen(MyPlayVideoActivity.this, true, true);
            }
        });


        checkBox.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked){
                FavoriteItem favoriteItem = new FavoriteItem();
                favoriteItem.img = xjVideo.getVod_pic();

                favoriteItem.title = xjVideo.getVod_name();

                favoriteItem.time = TimeUtils.getNowString();

                if (xjVideo.getType_id() == 2100){
                    favoriteItem.type = 2100;
                    favoriteItem.url = xjVideo.getVod_tag();
                }else if (xjVideo.getType_id() == 2200){
                    favoriteItem.type = 2200;
                    favoriteItem.url = xjVideo.getVod_tag();
                }else {
                    favoriteItem.type = 2000;
                    favoriteItem.url = xjVideo.getVod_id()+"";
                }

                favoriteItem.userName = userName;
                List<FavoriteItem> itemList = LitePal.where("url=? and userName=?",favoriteItem.url,userName).find(FavoriteItem.class);
                for (FavoriteItem item : itemList){
                    item.delete();
                }
                favoriteItem.save();
            }else {
                String url = xjVideo.getVod_id()+"";
                if (xjVideo.getType_id() == 2100){
                     url = xjVideo.getVod_tag();
                }else if (xjVideo.getType_id() == 2200){
                    url = xjVideo.getVod_tag();
                }
                List<FavoriteItem> itemList = LitePal.where("url=? and userName=?",url ,userName).find(FavoriteItem.class);
                for (FavoriteItem item : itemList){
                    item.delete();
                }
            }
        });
    }

    @Override
    public void showLoading(String key) {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public boolean isCancel() {
        return false;
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.snackbarText(message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }

    @Override
    public void playVideo(List<XJLookResult.InfoBean.PlayerListBean> player_list) {

        String url = player_list.get(0).getUrl();
        detailPlayer.setUp(url, true, "");
        detailPlayer.startPlayLogic();


        List<String> list = new ArrayList<>();
        list.add("https://cbu01.alicdn.com/img/ibank/2019/989/189/12940981989_392352300.jpg");
        list.add("https://cbu01.alicdn.com/img/ibank/2019/989/189/12940981989_392352300.jpg");
        banner.setImages(list)
                .setImageLoader(new GlideImageLoader())
                .setOnBannerListener(position -> {
                    Intent intent = new Intent();
                    intent.setAction("android.intent.action.VIEW");
                    Uri content_url = Uri.parse("https://www.lanzous.com/i8xnn8f");
                    intent.setData(content_url);
                    //        startActivity(intent);
                })
                .start();
        title.setText(xjVideo.getVod_name());
        checkBox.setVisibility(View.VISIBLE);
    }


    //推荐使用StandardGSYVideoPlayer，功能一致
    //CustomGSYVideoPlayer部分功能处于试验阶段
    @BindView(R.id.detail_player)
    StandardGSYVideoPlayer detailPlayer;


    private boolean isPlay;
    private boolean isPause;

    private OrientationUtils orientationUtils;


    @Override
    public void onBackPressedSupport() {

        if (orientationUtils != null) {
            orientationUtils.backToProtVideo();
        }

        if (GSYVideoManager.backFromWindowFull(this)) {
            return;
        }
        super.onBackPressedSupport();
    }


    @Override
    protected void onPause() {
        getCurPlay().onVideoPause();
        isPause = true;
        super.onPause();
    }

    @Override
    protected void onResume() {
        getCurPlay().onVideoResume(false);
        isPause = false;
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        if (isPlay) {
            getCurPlay().release();
            detailPlayer = null;
        }
        //GSYPreViewManager.instance().releaseMediaPlayer();
        if (orientationUtils != null)
            orientationUtils.releaseListener();

        super.onDestroy();

    }


    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        //如果旋转了就全屏
        if (isPlay && !isPause) {
            detailPlayer.onConfigurationChanged(this, newConfig, orientationUtils, true, true);
        }
    }


    private void resolveNormalVideoUI() {
        //增加title

    }

    private GSYVideoPlayer getCurPlay() {
        if (detailPlayer.getFullWindowPlayer() != null) {
            return detailPlayer.getFullWindowPlayer();
        }
        return detailPlayer;
    }


}
